﻿Imports System.Data
Imports FuncClasses
Imports System.Reflection
Imports System.Globalization
Imports System.Collections
Imports System.Collections.ObjectModel
Imports System.Threading
Imports System.Xml
Imports System.Threading.Tasks
Imports Microsoft.WindowsAPICodePack.Dialogs
Imports Microsoft.Win32

Partial Public Class Window1

#Region "Custom Layout Control Loading"
    Private CustomLayoutHolder As New Collection(Of Object)
    Private LayoutControl As UIElement
    Dim prop1 As DependencyProperty
    Dim prop2 As DependencyProperty

    ''' <summary>
    ''' Checks for .layout files in the main directory and creates an instance of it
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub RegisterLayout()
        ComboBox7.Items.Clear()
        LayoutGrid.Children.Remove(LayoutControl)

        For Each file As String In My.Computer.FileSystem.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory(), FileIO.SearchOption.SearchTopLevelOnly, "*.layout")
            Try
                Dim asm As Reflection.Assembly
                asm = Reflection.Assembly.Load(IO.File.ReadAllBytes(file))
                Dim params(0) As Object
                params(0) = Me
                ' Create object and cast to interface
                Dim typeName As String = System.IO.Path.GetFileNameWithoutExtension(file) + ".CustomLayout"  'CONVENTION: INITIALIZATION NameSpace: FileName(WithoutExtension).CustomLayout
                Dim ignoreCase As Boolean = True
                Dim bindingAttr As BindingFlags = BindingFlags.Default
                Dim binder As Binder = Nothing
                Dim args As Object() = params
                Dim culture As CultureInfo = Nothing
                Dim activationAttributes As Object() = Nothing
                Try
                    Dim temp As Object = asm.CreateInstance(typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes)
                    Dim temp2 As ICustomLayout = CType(temp, ICustomLayout)
                    CustomLayoutHolder.Add(temp)
                    Dispatcher.BeginInvoke(Sub()
                                               Dim item As New ComboBoxItem
                                               item.Content = temp2.Name
                                               ComboBox7.Items.Add(item)
                                           End Sub)
                Catch : End Try
            Catch ex As Exception : End Try
        Next
        Dispatcher.BeginInvoke(Sub()
                                   '### Load Last Layout ###'
                                   Dim lastlayout As String = loader.LastCustomLayout
                                   If String.IsNullOrEmpty(lastlayout) Then
                                       LoadLayoutControl("Standardlayout")
                                       ComboBox7.Text = "Standardlayout"
                                   Else
                                       LoadLayoutControl(lastlayout)
                                       ComboBox7.Text = lastlayout
                                   End If
                               End Sub)
    End Sub

    Private Sub LoadLayoutControl(Name As String)
        For Each item As Object In CustomLayoutHolder
            Dim temp As ICustomLayout = CType(item, ICustomLayout)
            If temp.Name = Name Then
                Try
                    LayoutControl = CType(item, UIElement)
                    Try
                        prop1 = DependencyProperty.Register("HorizontalAlignment", GetType(HorizontalAlignment), LayoutControl.GetType)
                        prop2 = DependencyProperty.Register("VerticalAlignment", GetType(VerticalAlignment), LayoutControl.GetType)

                        LayoutControl.SetValue(prop1, HorizontalAlignment.Stretch)
                        LayoutControl.SetValue(prop2, VerticalAlignment.Top)
                    Catch ex As Exception
                        'Already registered
                    End Try
                    LayoutGrid.Children.Clear()
                    LayoutGrid.Children.Add(LayoutControl)
                    currentLayout = temp
                    loader.LastCustomLayout = temp.Name
                    Exit Sub
                Catch ex As Exception : End Try
            End If
        Next
    End Sub
#End Region

#Region "Public Properties"
    Public Shared ReadOnly Property Version As Decimal
        Get
            Return 1.493
        End Get
    End Property

    Public ReadOnly Property SettingsViewModel As VariousSettingsViewModel
        Get
            Return settingsvm
        End Get
    End Property

    Public ReadOnly Property CustomerViewModel As CustomerViewModel
        Get
            Return customervm
        End Get
    End Property

    Public ReadOnly Property OrderViewModel As OrderViewModel
        Get
            Return ordervm
        End Get
    End Property

    Public ReadOnly Property ArticleViewModel As ArticleViewModel
        Get
            Return articlevm
        End Get
    End Property

    ''' <summary>
    ''' Gibt das Hauptsteuerlement zurück, auf der alle anderen Controls platziert sind.
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public ReadOnly Property MainGrid As Grid
        Get
            Return GridMain
        End Get
    End Property

    ''' <summary>
    ''' Method to add a new License to Licensepage
    ''' </summary>
    ''' <param name="Programmname">The part of the Programm, you licensed</param>
    ''' <param name="license">The Licensename</param>
    ''' <param name="licensecontent">The content of the license itself</param>
    ''' <remarks></remarks>
    Public Sub AddNewLicense(ByVal Programmname As String, license As String, licensecontent As String)
        Dispatcher.BeginInvoke(Sub()
                                   BackStageLicenses.Items.Add(New License(Programmname, license, licensecontent))
                               End Sub)
    End Sub

    ''' <summary>
    ''' Adds a New RibbonTab and TabItem to the view
    ''' </summary>
    ''' <param name="ribbontab">The Fluent.RibbonTabItem</param>
    ''' <param name="tabitem">The Tabitem which contains your data you want to show</param>
    ''' <returns>True when success, otherwise false</returns>
    ''' <remarks></remarks>
    Public Function AddNewRibbonTab(ByRef ribbontab As Fluent.RibbonTabItem, Optional ByRef tabitem As TabItem = Nothing) As Boolean
        If ribbontab IsNot Nothing Then
            _ribbon.Tabs.Insert(IndexOfLastNormalRibbonTab, ribbontab)
            If tabitem IsNot Nothing Then
                TabControl1.Items.Add(tabitem)
            End If
            addinribbons.Add(New KeyValuePairs(ribbontab, tabitem))
            Return True
        End If
        Return False
    End Function

    ''' <summary>
    ''' Adds a New RibbonTab and TabItem to the view
    ''' </summary>
    ''' <param name="ribbontab">The Fluent.RibbonTabItem</param>
    ''' <param name="tabitem">The Tabitem which contains your data you want to show</param>
    ''' <returns>True when success, otherwise false</returns>
    ''' <remarks></remarks>
    Public Function AddNewContextualRibbonTab(ByRef ribbontab As Fluent.RibbonTabItem, Optional ByRef tabitem As TabItem = Nothing) As Boolean
        If ribbontab IsNot Nothing Then
            _ribbon.Tabs.Add(ribbontab)
            If tabitem IsNot Nothing Then
                TabControl1.Items.Add(tabitem)
            End If
            addinribbons.Add(New KeyValuePairs(ribbontab, tabitem))
            Return True
        End If
        Return False
    End Function

    ''' <summary>
    ''' Adds a new control to the welcome page on startup
    ''' </summary>
    ''' <param name="control"></param>
    ''' <remarks></remarks>
    Public Sub AddNewWelcomeInfo(ByRef control As UIElement)
        WelcomeRightSP.Children.Add(control)
    End Sub

    ''' <summary>
    ''' Removes a control from the welcome page
    ''' </summary>
    ''' <param name="control"></param>
    ''' <remarks></remarks>
    Public Sub RemoveWelcomeInfo(ByRef control As UIElement)
        WelcomeRightSP.Children.Remove(control)
    End Sub

    Public Shared ReadOnly Property AppID As String
        Get
            Dim t As String = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\LastElb Productions\Biller", "AppID", "")
            If String.IsNullOrEmpty(t) Then
                Dim gstring = Guid.NewGuid.ToString
                t = gstring
                My.Computer.Registry.SetValue("HKEY_LOCAL_MACHINE\SOFTWARE\LastElb Productions\Biller", "AppID", gstring)
            End If
            Return t
        End Get
    End Property

    Public ReadOnly Property Database As IDatabase
        Get
            Return loader
        End Get
    End Property

    Public ReadOnly Property ExportLayout As ICustomLayout
        Get
            Return currentLayout
        End Get
    End Property

    Public Function AddSettingsTab(ByRef tab As TabItem) As Boolean
        Try
            SettingsTabControl.Items.Add(tab)
            Return True
        Catch ex As Exception
            log.AddEntry(ex.ToString)
            Return False
        End Try
    End Function

    Public Function AddSettingsTab(ByVal header As String, ByVal _body As UIElement) As TabItem
        Try
            Dim tab = New TabItem With {.Content = _body, .Header = header}
            SettingsTabControl.Items.Add(tab)
            Return tab
        Catch ex As Exception
            log.AddEntry(ex.ToString)
            Return Nothing
        End Try
    End Function

    Public Function RemoveSettingsTab(ByRef tab As TabItem) As Boolean
        Try
            SettingsTabControl.Items.Remove(tab)
            Return True
        Catch ex As Exception
            log.AddEntry(ex.ToString)
            Return False
        End Try
    End Function

#End Region

#Region "Privates"
    Private addinribbons As New Collection(Of KeyValuePairs)

    Private Property WarningCustomerDelete As Boolean
        Get
            Return loader.GetSettingByKey("CustomerDelete")
        End Get
        Set(value As Boolean)

        End Set
    End Property

    Private Property WarningArticleDelete As Boolean
        Get
            Return loader.GetSettingByKey("ArticleDelete")
        End Get
        Set(value As Boolean)

        End Set
    End Property

    Private Property WarningOrderDelete As Boolean
        Get
            Return loader.GetSettingByKey("AuftragDelete")
        End Get
        Set(value As Boolean)

        End Set
    End Property
#End Region

#Region "Public Events"
    ''' <summary>
    ''' Dieses Ereignis wird ausgelöst, wenn der Benutzer im Einstellungentab den Speichern-Button für geänderte Layouteinstellungen klickt.
    ''' </summary>
    ''' <param name="LayoutName">Dieser String enthält den Namen des momentan ausgewählten Layouts</param>
    ''' <remarks>Dieses Ereignis wird bald entfernt und durch eine neue Methode im Interface ersetzt.</remarks>
    Public Event SaveLayoutSettings(ByVal LayoutName As String)
    Public Event CompanyChanged()

    Public Event GeneratePDF(ByVal path As String, ByVal Auftrag As Order)
    Public Event PrintPDF(ByVal path As String, ByVal Auftrag As Order)

    Public Event OrderLoaded(auftrag As Order)
    Public Event NewOrder(auftrag As Order)
    Public Event OrderSaved(auftrag As Order)

    Public Event CutomerLoaded(customer As Customer)
    Public Event NewCustomer(customer As Customer)
    Public Event CustomerSaved(customer As Customer)

    Public Event ArticleLoaded(articel As Article)
    Public Event NewArticle(articel As Article)
    Public Event ArticleSaved(articel As Article)
#End Region
End Class